home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 26 / Cream of the Crop 26.iso / program / ddj0897.zip / RCSC.ZIP / DEMO51 / MCHOPSTK.C < prev    next >
C/C++ Source or Header  |  1997-01-12  |  1KB  |  42 lines

  1. #include <stdio.h>
  2.  
  3. /* data for the chopstick monitor */
  4. static int chopsticks[] = {2, 2, 2, 2, 2};    /* chopstick counts */
  5. static int myright[] = {1, 2, 3, 4, 0};        /* right neighbor identity */
  6. static int myleft[] = {4, 0, 1, 2, 3};        /* left neighbor identity */
  7. static CONDITION waiting[5];            /* condition variables */
  8.  
  9. /* initialization for chopstick monitor */
  10. void monitor mchopstk()
  11. {
  12.     /* this is being called during initialization */
  13. }
  14.  
  15. /* monitor entry to get both chopsticks */
  16. void entry GetChopsticks(id)
  17. int id;
  18. {
  19.     /* wait until both chopsticks available */
  20.     if (chopsticks[id] != 2)
  21.         Wait(&waiting[id]);
  22.  
  23.     /* decrement neighbors' chopstick counts */
  24.     chopsticks[myright[id]]--;
  25.     chopsticks[myleft[id]]--;
  26. }
  27.  
  28. /* monitor entry to release the 2 chopsticks */
  29. void entry PutChopsticks(id)
  30. int id;
  31. {
  32.     /* increment neighbors' chopstick counts and wake 
  33.         them up if they now have both chopsticks */
  34.     if (++chopsticks[myright[id]] == 2)
  35.         Signal(&waiting[myright[id]]);
  36.         
  37.     if (++chopsticks[myleft[id]] == 2)
  38.         Signal(&waiting[myleft[id]]);
  39.         
  40. }
  41.  
  42.